/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import banco.ConnectionFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import modelo.Usuario;

/**
 *
 * @author bruno
 */
public class UsuarioDAOImp implements UsuarioDAO {

    private Connection conn;

    public UsuarioDAOImp() throws Exception {
        try {
            this.conn = ConnectionFactory.getConnection();

        } catch (Exception e) {
            throw new Exception("Erro: "
                    + "\n" + e.getMessage());
        }
    }

    @Override
    public List<Usuario> mostraTodos() throws Exception {
        PreparedStatement ps = null;
        Connection conn = null;
        ResultSet rs = null;
        List<Usuario> lista = new ArrayList<Usuario>();
        try {
            String SQL = "SELECT * FROM TB_USUARIO";
            conn = this.conn;
            ps = conn.prepareStatement(SQL);
            rs = ps.executeQuery();
            while (rs.next()) {
                Usuario usuario = new Usuario();
                usuario.setId(rs.getInt("USU_ID"));
                usuario.setNome(rs.getString("USU_NOME"));
                usuario.setLogin(rs.getString("USU_LOGIN"));
                usuario.setPassword(rs.getString("USU_PASS"));
                usuario.setPermissao(rs.getString("USU_PERMI"));
                lista.add(usuario);
            }

        } catch (SQLException sqle) {
            throw new Exception("Erro ao pesquisar dados " + sqle);
        } finally {
            ConnectionFactory.closeConnection(conn, ps, rs);
            return lista;
        }
    }

    public void gravar(Usuario umUsuario) throws Exception {
        PreparedStatement ps = null;
        Connection conn = null;
        if (umUsuario == null) {
            throw new Exception("O valor passado não pode ser nulo");
        }

        try {
            String SQL = "INSERT INTO TB_USUARIO (USU_NOME, USU_LOGIN, USU_PASS, "
                    + " USU_PERMI) "
                    + "values (?, ?, ?, ?)";
            conn = this.conn;
            ps = conn.prepareStatement(SQL);
            ps.setString(1, umUsuario.getNome());
            ps.setString(2, umUsuario.getLogin());
            ps.setString(3, umUsuario.getPassword());
            ps.setString(4, umUsuario.getPermissao());
            ps.executeUpdate();

        } catch (SQLException sqle) {
            throw new Exception("Erro ao inserir dados " + sqle);
        } finally {
            ConnectionFactory.closeConnection(conn, ps);
        }
    }
}
